
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Divider, Button, Modal, Form, Input, Row, Col, Select, Checkbox, Table, Card, Icon, Popconfirm, message, Pagination, Switch, TextArea} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
// import styles from './style.less';

import PublicTableWrapper from '@/components/TableForm'


const QRCode = require('qrcode.react')

const routes = [
    {
      path: '',
      breadcrumbName: 'Mange GW',
    },
    {
      path: '',
      breadcrumbName: 'Mange GW',
    }
]



// 新增网关
const AddAdministrator = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
      
      render() {
        const { visible, onCancel, onCreate, form,  } = this.props
        const { getFieldDecorator } = form
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }

        return (
            <Modal
                visible={visible}
                title="Add GW"
                onCancel={onCancel}
                onOk={onCreate}
                okText="Confirm"
                forceRender
            >
                <Form style={{ margin: '0 auto' }}>
                    <Row gutter={24}>
                        <Col span={24}>
                            <Form.Item label="GW IMEI:" {...formItemLayout} required={false}>
                                {getFieldDecorator('imei', {
                                rules: [{ required: true, message: 'Please input!' }, { len: 15, message: 'Please input 15 digits IMEI'}],
                                })(<Input.TextArea placeholder="input 15 digits IMEI!" autoSize={{ minRows: 3, maxRows: 5 }}/>)}
                            </Form.Item>
                        </Col>
                        
                        
                    </Row>
                </Form>
            </Modal>
        )
      }
    }
)


// 关联网关
const AboutGateWay = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
      state = {
        data: [
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
            { Code: '1232321421421' },
        ],
        columns: [
            {
                title: 'Account',
                dataIndex: 'Accout',
            },
            {
                title: 'Name',
                dataIndex: 'Name',
            },
            // {
            //     title: 'Operation',
            //     dataIndex: 'option',
            //     valueType: 'option',
            //     width: 150,
            //     render: (_, record) => (
            //         <>
            //             <a 
            //                 style={{color: 'red'}}
            //                 onClick={() => this.deleteClick(record)}
            //             >
            //                 删除
            //             </a>
            //         </>
            //     ),
            // },
        ],
      }

    handleSearch = () => {
        const { form, gatewaysListSearch } = this.props
        
        form.validateFields((err, values) => {
            if (err) { return}
            gatewaysListSearch(values)
            
        })
        
    }

    handleReset = () => {
        this.props.form.resetFields()
    }

    deleteClick = record => {
        const { gatewaysDelete } = this.props
        gatewaysDelete(record)
    }

    // 表格选择
    onSelectChange = selectedRowKeys => {
        this.props.selectMethod(selectedRowKeys)
    }

    render() {
        const { visible, onCancel, onCreate, form,  } = this.props
        const { getFieldDecorator } = form
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }

        const rowSelection = {
            selectedRowKeys: this.props.selectedRowKeys,
            onChange: this.onSelectChange,
        }

        return (
            <Modal
                visible={visible}
                title="GW Assgnmt"
                onCancel={onCancel}
                onOk={onCreate}
                // forceRender
                width="60%"
            >
                <>
                    <Form style={{ margin: '0 auto' }}>
                        <Row gutter={24}>
                            <Col span={8}>
                                <Form.Item label={false} {...formItemLayout} required={false}>
                                    <Icon type="search" />
                                    {getFieldDecorator('accout', { })(
                                        <Input placeholder="Input account"
                                            style={{width: '80%', marginLeft: '10px', borderTop: '0px', borderLeft: '0px', borderRight: '0px'}}
                                        />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                            <Form.Item style={{ display: 'flex' }}>
                                <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
                                Query
                                </Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                Reset
                                </Button>
                            </Form.Item>
                        </Col>
                        </Row>
                    </Form>
                    <Table
                        rowKey="key"
                        dataSource={this.props.data}
                        columns={this.state.columns}
                        pagination={{
                            defaultPageSize: 7
                        }}
                        rowSelection={rowSelection}
                    ></Table>
                </>
            </Modal>
        )
      }
    }
)





@connect(({ gateway }) => ({
    gateway
}))


class Management extends Component {
    state = {
        selectedRowKeys: [],
        // 关联网关弹窗
        gatewayVisible: false,
        // 关联网关数据
        gatewaysList: [],
        // 关联网关原始数据
        gatewaysOringeList: [],
        // 关联网关编辑对象
        gatewaysEditObj: {},
        // 查看二维码
        qrVisit: false,
        qrContent: {
            url: '',
            imei: ''
        },
        // 表格
        columns: [
            {
                title: 'GW IMEI',
                dataIndex: 'name',
            },
            {
                title: 'Curr ACK settings',
                dataIndex: 'currentAckTime',
                render: (_, record) => (
                    <span>{record.currentAckTime ? moment.utc(Number(record.currentAckTime)).format("YYYY-MM-DD hh:mm:ss") : "-"}</span>
                )
            },
            {
                title: 'New ACK settings',
                dataIndex: 'latestAckTime',
                render: (_, record) => (
                    <span>{record.latestAckTime ? moment.utc(Number(record.latestAckTime)).format("YYYY-MM-DD hh:mm:ss") : "-"}</span>
                )
            },
            {
                title: 'Last Rpt time',
                dataIndex: 'latestMessageTime',
                render: (_, record) => (
                    <span>{record.latestMessageTime ? moment.utc(Number(record.latestMessageTime)).format("YYYY-MM-DD hh:mm:ss") : "-"}</span>
                )
            },
            {
                title: 'QRCode',
                dataIndex: 'qrcode',
                render: (_, record) => (
                    <>
                        <QRCode value={`{IMEI:${record.name}}`} size={30} onClick={() => this.checkQrcode(record)}/>
                    </>
                ),
            },
            {
                title: 'On/Off',
                dataIndex: 'status',
                align: 'center',
                render: (_, record) => (
                    <>
                        <Switch
                            checkedChildren="On"
                            unCheckedChildren="Off"
                            defaultChecked
                            checked={!!record.status}
                            onChange={() => this.statusOnchange(record)}
                        />
                    </>
                ),
                
            },
            {
                title: 'Operation',
                dataIndex: 'option',
                valueType: 'option',
                render: (_, record, index) => (
                    <>
                        <a
                            onClick={() => this.showUser(_, record)}
                        >Assgnmt</a>
                        <Divider type="vertical" />
                        <a 
                            style={{color: 'red'}}
                            onClick={() => this.showConfirm(record)}
                        >
                            delete
                        </a>
                    </>
                ),
            },
        ],

        loading: false,
        data: [],
        page: 1,
        pageSize: 10,
        search: "",
        totalCount: 1,
        
    }

    componentDidMount () {
        this.initfetch()
    }

    initfetch = () => {
        const { dispatch } = this.props
        const { page, pageSize, search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'gateway/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }

    // 新增网关
    showModal = () => {
        this.setState({ visible: true })
    }

    // 新增网关确定
    onCreate = () => {
        const { form } = this.formRef.props
        const { dispatch } = this.props

        form.validateFields((err, values) => {
            if (err) { return}
            dispatch({
                type: 'gateway/addGateway',
                payload: values,
            }).then(res => {
                if (res.status === 200) {
                    this.setState({
                        visible: false
                    })
                    this.initfetch()
                }
            })



        })
    }

    // 关联用户
    saveGateWayFormRef = formRef => { this.saveGateWayFormRef = formRef }

    showUser = (_, record) => {
        // 
        const { dispatch } = this.props
        const selectedList = []
        record.Users.map(item => {
            selectedList.push(item.Id)
            return 200
        })
        dispatch({
            type: 'gateway/fetchUser',
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    gatewaysList: res.data,
                    gatewaysOringeList: res.data,
                    selectedRowKeys: selectedList,
                    gatewaysEditObj: record
                })
            }
            this.setState({gatewayVisible: true})
        })
    }

    // 关联用户搜索
    gatewaysListSearch = values => {
        const { gatewaysOringeList } = this.state
        if (values.accout !== undefined && values.accout !== "") {
            const data = []
            gatewaysOringeList.map(item => {
                if (item.Accout.includes(values.accout)) {
                    data.push(item)
                }
                return 200
            })
            this.setState({
                gatewaysList: data
            })
            return;
        }

        this.setState({
            gatewaysList: gatewaysOringeList
        })
    }

    selectMethod = seleceList => {
        this.setState({
            selectedRowKeys: seleceList
        })
    }

    okUsers = () => {
        // 改变的是哪个gateway表
        // 改变了关联哪几个用户
        const { gatewaysEditObj, selectedRowKeys} = this.state

        const { dispatch } = this.props
        dispatch({
            type: 'gateway/fetchOneGateway',
            payload: {
                Id: gatewaysEditObj.id,
                select: selectedRowKeys
            },
        }).then(res => {
            if(res.status === 200) {
                this.initfetch()
            }
        })



        this.setState({ gatewayVisible: false })
    }

    showConfirm = record => {
        const isThis = this
        const { dispatch } = this.props
        Modal.confirm({
            title: 'confirm deletion',
            content: (<div><span style={{color: 'red'}}>The deletion is irrevocable.</span><span style={{color: '#5E5E5E'}}>Do you want to continue?</span></div>),
            onOk() {
                dispatch({
                    type: 'gateway/deleceGateway',
                    payload: record
                }).then(res => {
                    if (res.status === 200) {
                        isThis.initfetch()
                        message.success('success')
                    } else {
                        message.success('error')
                    }
                })


            },
            onCancel() {},
        })
    }

    statusOnchange = record => {
        const { dispatch } = this.props

        dispatch({
            type: 'gateway/daclGateway',
            payload: record,
        }).then(res =>{
            if(res.status === 200) {
                // dispatch请求成功后
                const { data } = this.state
                // eslint-disable-next-line array-callback-return
                data.map(values => {
                    if (values.key === record.key) {
                        // eslint-disable-next-line no-param-reassign
                        values.status = !values.status
                    }
                })
                this.setState({
                    data
                })
            }
        })
        
    }

    // 分页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        })
        
        const { dispatch } = this.props
        const { search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'gateway/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }

    handleSearch = () => {
        const { form } = this.props
        const mapObj = {
            imei: 'code__contains',
        }
        const searchList = []
        form.validateFields((err, values) => {
            if (err) { return}
            Object.keys(values).forEach(key => {
                if (values[key] !== undefined && values[key] !== '' ) {
                    searchList.push(`${mapObj[key]}:${values[key]}`);
                }
            })

        })
        const searchString = `&query=${searchList.join(',')}`;
        // search record
        this.setState({
            search: searchString,
        })
        // fetch data
        const { dispatch } = this.props
        const { page, pageSize } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'gateway/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search: searchString
              },
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }
        })
    }

    handleReset = () => {
        this.props.form.resetFields()
    }

    // 查看二维码
    checkQrcode = record => {
        this.setState({ qrVisit: true, qrContent: {url: record.qrcode, imei: record.name} })
    }

    // 所有弹窗取消
    onCancel = () => {
        this.setState({ qrVisit: false, visible: false, gatewayVisible: false })
    } 


    saveFormRef = formRef => { this.formRef = formRef }



    render () {
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }
        const { getFieldDecorator } = this.props.form


        return (
            <PageHeaderWrapper title="Mange GW" breadcrumb={{ routes }}>
                <Card>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="GW IMEI" {...formItemLayout}>
                                {getFieldDecorator('imei')(
                                    <Input placeholder="Input Gateway IMEI" />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item style={{ display: 'flex' }}>
                                <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
                                Query
                                </Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                Reset
                                </Button>
                            </Form.Item>
                        </Col>
                    
                    </Row>


                    <Button icon="plus" type="primary" style={{marginBottom: '10px'}} onClick={this.showModal}>Add GW</Button>

                    <PublicTableWrapper
                        loading={this.state.loading}
                        columns={this.state.columns}
                        data={this.state.data}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange={(page, pageSize) => this.paginationChange(page, pageSize)}
                    />

                </Card>

                <Modal
                    visible={this.state.qrVisit}
                    title="QRCode"
                    onCancel={this.onCancel}
                    onOk={this.onCancel}
                >
                    <div style={{position: "relative", width: "100%", display: "flex", flexDirection: "column", alignItems: "center", padding: "15px"}}>
                        <h4>IMEI:{this.state.qrContent.imei}</h4>
                        <QRCode value={`{IMEI:${this.state.qrContent.imei}}`} size={180} />
                    </div>
                </Modal>

                <AddAdministrator
                    wrappedComponentRef={this.saveFormRef}
                    visible={this.state.visible}
                    onCancel={this.onCancel}
                    onCreate={this.onCreate}
                />

                <AboutGateWay
                    wrappedComponentRef={this.saveGateWayFormRef}
                    visible={this.state.gatewayVisible}
                    onCancel={this.onCancel}
                    onCreate={this.okUsers}
                    data={this.state.gatewaysList}
                    gatewaysListSearch={this.gatewaysListSearch}
                    gatewaysDelete={this.gatewaysDelete}
                    selectedRowKeys={this.state.selectedRowKeys}
                    selectMethod={this.selectMethod}
                />


            </PageHeaderWrapper>
        )

    }

}



// export default Management
export default Form.create()(Management)